package de.playmee.handler;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DatabaseHandler {
	
	private final String TAG = "DatabaseHandler";
	
	protected final static String DELIMITER = ",";
	
	protected DatabaseHelper dbHelper;
	protected SQLiteDatabase db;
	
	protected DatabaseHandler(DatabaseHelper dbHelper) {
		this.dbHelper = dbHelper;
	}
	
	/**
	 * opens the database for writing
	 */
	public void openForWriting() {
		synchronized(dbHelper) {
			db = dbHelper.getWritableDatabase();
		}
		Log.i(TAG, "Database opened");
	}
	
	/**
	 * opens the database for reading
	 */
	public void openForReading() {
		synchronized(dbHelper) {
			db = dbHelper.getReadableDatabase();
		}
		Log.i(TAG, "Database opened.");
	}
	
	/**
	 * closes the database
	 */
	public void close() {
		synchronized(dbHelper) {
			dbHelper.close();
		}
		Log.i(TAG, "Database closed.");
	}
	
	/**
	 * gets the count of available rows
	 * 
	 * @param table
	 * @return count
	 */
	public int getCount(String table, String selection) {
		int count = 0;
		String query = "SELECT count(*) FROM " + table;
		if (selection != null && !selection.isEmpty()) {
			query += " WHERE " + selection;
		}
		synchronized(db) {
			Cursor cursor = db.rawQuery(query, null);
			if (cursor != null && cursor.moveToFirst()) {
				count = cursor.getInt(0);
			}
			cursor.close();
		}
		return count;
	}
	
	/**
	 * checks if the table is empty
	 * 
	 * @param table
	 * @return true if the table is empty, false otherwise
	 */
	public boolean tableIsEmpty(String table) {
		int count = getCount(table, null);
		if (count == 0) {
			Log.i(TAG, "Table is empty.");
			return true;
		} else {
			Log.i(TAG, "Table is not empty. " + count + " entries found.");
			return false;
		}
	}
}
